package com.yuexunit.mobilenurse.module.SignInput.ui;

import android.content.Context;
import android.os.Bundle;
import android.text.InputType;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;

import com.yuexunit.mobilenurse.R;
import com.yuexunit.mobilenurse.config.AppConfig;
import com.yuexunit.mobilenurse.config.Contracts;
import com.yuexunit.mobilenurse.module.SignInput.adapter.SignTypeAdapter;
import com.yuexunit.mobilenurse.module.SignInput.bean.Sqlite_SignInputBean;
import com.yuexunit.mobilenurse.module.SignInput.model.impl.SignModel;
import com.yuexunit.mobilenurse.module.SignInput.presenter.impl.SignPresenter;
import com.yuexunit.mobilenurse.module.SignInput.ui.view.ISignInput;
import com.yuexunit.mobilenurse.widget.LoadingDialog;

import org.kymjs.kjframe.KJActivity;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;
import org.kymjs.kjframe.utils.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by sslcjy on 16/1/26.
 */
public class Act_Signs_Input extends KJActivity implements ISignInput {
    @Bind(R.id.signinput_name)
    TextView signinputName;
    @Bind(R.id.signinput_bedno)
    TextView signinputBedno;
    @Bind(R.id.signinput_visitno)
    TextView signinputVisitno;
    @Bind(R.id.sign_time_day)
    TextView signTimeDay;
    @Bind(R.id.sign_time_hour)
    Spinner signTimeHour;
    @Bind(R.id.sign_temp_spinner)
    Spinner signTempSpinner;
    @Bind(R.id.sign_temp_edt)
    EditText signTempEdt;
    @Bind(R.id.sign_rate_spinner)
    Spinner signRateSpinner;
    @Bind(R.id.sign_rate_edt)
    EditText signRateEdt;
    //    @Bind(R.id.types_list)
//    FixedSwipeListView typesList;
    @Bind(R.id.sign_scroll)
    ScrollView signScroll;
    @Bind(R.id.bp_high)
    EditText bpHigh;
    @Bind(R.id.bp_low)
    EditText bpLow;
    @Bind(R.id.breathe_edit)
    EditText breatheEdit;
    @Bind(R.id.pain_edit)
    EditText painEdit;
    @Bind(R.id.shit_edit)
    EditText shitEdit;
    @Bind(R.id.input_edit)
    EditText inputEdit;
    @Bind(R.id.output_edit)
    EditText outputEdit;
    @Bind(R.id.weight_edit)
    EditText weightEdit;
    @Bind(R.id.height_edit)
    EditText heightEdit;
    @Bind(R.id.upd_edit)
    EditText updEdit;
    private SignPresenter presenter;

    //病人相关信息
    public String inpNo;//住院号
    public String recorder;//记录人员姓名
    public String name;//病人姓名
    public Sqlite_SignInputBean currentbean;//存入数据库的当前病人相关信息
    public String sign_hour;//输入病人的时间
    //体征显示界面的adpater
    private SignTypeAdapter adapter;

    public String temp;//体温类型
    public String rate;//rate类型
    private String[] temp_code;
    private String[] rate_code;

    private ArrayList<String> date = new ArrayList<>();

    private int position = 0;
    private LoadingDialog dialog;

    @Override
    public void setRootView() {
        setContentView(R.layout.act_signs_input);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        super.initData();
        dialog = new LoadingDialog(aty);
        presenter = new SignPresenter(new SignModel(), this);
        temp_code = this.getResources().getStringArray(R.array.temp_code);
        rate_code = this.getResources().getStringArray(R.array.rate_code);
        inpNo = PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_VISITNO);
        recorder = PreferenceHelper.readString(aty, AppConfig.NURSE_INFO, AppConfig.NURSE_LOGID);
        name = PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_NAME);
    }


    @Override
    public void initWidget() {
        super.initWidget();
        signinputName.setText(PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_NAME));
        signinputBedno.setText(PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_BEDCODE));
        signinputVisitno.setText(inpNo);
        signTimeDay.setText(StringUtils.getDataTime("yyyy-MM-dd"));
        signTimeHour.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                sign_hour = (String) parent.getItemAtPosition(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        signTempSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                temp = temp_code[position];
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        signRateSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                rate = rate_code[position];
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

//        typesList.setFocusable(false);
//        adapter = new SignTypeAdapter(typesList, Contracts.signMenuList, R.layout.item_type);
//        typesList.setAdapter(adapter);

        signTempEdt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        signRateEdt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        bpHigh.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        bpLow.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        painEdit.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        breatheEdit.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        shitEdit.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        inputEdit.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        outputEdit.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        weightEdit.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        heightEdit.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        updEdit.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
    }

    @OnClick(R.id.titlebar_img_back)
    public void out() {
        finish();
    }

    @OnClick({R.id.titlebar_img_menu, R.id.right_text})
    public void uploadMenu() {
        dialog.show();
        date = new ArrayList<>();
        if(signTempEdt.getText().length()>0)
        {
            date.add(temp + ":" + signTempEdt.getText());
        }
        if(signRateEdt.getText().length()>0)
        {
            date.add(rate + ":" + signRateEdt.getText());
        }

        if(bpHigh.getText().length()>0)
        {
            date.add("1072:" + bpHigh.getText());
        }
        if(bpLow.getText().length()>0)
        {
            date.add("397:" + bpLow.getText());
        }
        if(breatheEdit.getText().length()>0)
        {
            date.add("18:" + breatheEdit.getText());
        }
        if(painEdit.getText().length()>0)
        {
            date.add("453:" + painEdit.getText());
        }
        if(shitEdit.getText().length()>0)
        {
            date.add("3:" + shitEdit.getText());
        }
        if(inputEdit.getText().length()>0)
        {
            date.add("42:" + inputEdit.getText());
        }
        if(outputEdit.getText().length()>0)
        {
            date.add("43:" + outputEdit.getText());
        }
        if(weightEdit.getText().length()>0)
        {
            date.add("1201:" + weightEdit.getText());
        }
        if(heightEdit.getText().length()>0)
        {
            date.add("257:" + heightEdit.getText());
        }
        if(updEdit.getText().length()>0)
        {
            date.add("4:" + updEdit.getText());
        }

        if(date.size()>0)
        {
            position = 0;
            Map<String, String> params = new HashMap<>();
            params.put("inpNo", inpNo);
            params.put("timestamp", StringUtils.getDataTime("yyyy-MM-dd HH:mm:ss"));
            params.put("recorder", recorder);
            params.put("signData", date.get(0));
            params.put("timepoint", StringUtils.getDataTime("yyyy-MM-dd") + " " + sign_hour + ":00:00");
            presenter.uploadTypesInfo(params, name);
        }
    }


    @Override
    public void uploadSignValue(String buildItem) {
        StringBuilder builder = new StringBuilder();
        if (!StringUtils.isEmpty(signTempEdt.getText())) {
            if (builder.length() != 0) {
                builder.append("," + temp + ":" + signTempEdt.getText());
            } else {
                builder.append(temp + ":" + signTempEdt.getText());
            }
        }

        if (!StringUtils.isEmpty(signRateEdt.getText())) {
            if (builder.length() != 0) {
                builder.append("," + rate + ":" + signRateEdt.getText());
            } else {
                builder.append(rate + ":" + signRateEdt.getText());
            }
        }

        if (builder.length() != 0 && !buildItem.isEmpty()) {
            builder.append("," + buildItem);
        } else {
            builder.append(buildItem);
        }

        Map<String, String> params = new HashMap<>();
        params.put("inpNo", inpNo);
        params.put("timestamp", StringUtils.getDataTime("yyyy-MM-dd HH:mm:ss"));
        params.put("recorder", recorder);
        params.put("signData", builder.toString());
        params.put("timepoint", StringUtils.getDataTime("yyyy-MM-dd") + " " + sign_hour + ":00:00");
        presenter.uploadTypesInfo(params, name);

        finish();
    }

    @Override
    public void overSignInputFailed() {
        if(position != (date.size()-1))
        {
            position++;
            Map<String, String> params = new HashMap<>();
            params.put("inpNo", inpNo);
            params.put("timestamp", StringUtils.getDataTime("yyyy-MM-dd HH:mm:ss"));
            params.put("recorder", recorder);
            params.put("signData", date.get(position));
            params.put("timepoint", StringUtils.getDataTime("yyyy-MM-dd") + " " + sign_hour + ":00:00");
            presenter.uploadTypesInfo(params, name);
        }
        else {
            dialog.dismiss();
            ViewInject.toast("体征上传完成");
            finish();
        }
    }

    @Override
    public void overSignInputSuccess() {
        if(position != (date.size()-1))
        {
            position++;
            Map<String, String> params = new HashMap<>();
            params.put("inpNo", inpNo);
            params.put("timestamp", StringUtils.getDataTime("yyyy-MM-dd HH:mm:ss"));
            params.put("recorder", recorder);
            params.put("signData", date.get(position));
            params.put("timepoint", StringUtils.getDataTime("yyyy-MM-dd") + " " + sign_hour + ":00:00");
            presenter.uploadTypesInfo(params, name);
        }
        else {
            dialog.dismiss();
            ViewInject.toast("体征上传完成");
            finish();
        }
    }

    /**
     * 通过dispatchTouchEvent每次ACTION_DOWN事件中动态判断非EditText本身区域的点击事件，然后在事件中进行屏蔽。然后当点击不是EditText时候，进行隐藏键盘操作
     *
     * @param ev
     * @return
     */

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {

        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件\
                return false;
            } else {
                return true;
            }
        }
        return false;
    }
}
